require('dotenv').config();
const express = require('express');
const mongoose = require('mongoose');
const cors = require('cors');
const helmet = require('helmet');
const rateLimit = require('express-rate-limit');

// 导入路由
const authRoutes = require('./routes/auth');
const userRoutes = require('./routes/users');
// const travelRoutes = require('./routes/travel'); // 未使用，已注释
const logger = require('./utils/logger');

const app = express();

// 安全中间件
app.use(helmet());

// 限流中间件
const limiter = rateLimit({
  windowMs: 15 * 60 * 1000, // 15分钟
  max: 100, // 限制每个IP每15分钟最多100个请求
  message: {
    error: '请求过于频繁，请稍后再试'
  }
});
app.use(limiter);

// CORS配置 - 支持Flutter Web
app.use(cors({
  origin: [
    'http://localhost:3000',
    'http://localhost:8080', 
    'http://127.0.0.1:8080',
    'http://localhost:8081',
    'http://127.0.0.1:8081',
    // Flutter Web 端口
    'http://localhost:55907',
    'http://127.0.0.1:55907',
    'http://localhost:5000',
    'http://127.0.0.1:5000',
    // 动态端口支持
    /^http:\/\/localhost:\d+$/,
    /^http:\/\/127\.0\.0\.1:\d+$/,
    process.env.FLUTTER_APP_URL
  ].filter(Boolean),
  credentials: true,
  optionsSuccessStatus: 200,
  methods: ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'],
  allowedHeaders: ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept', 'Origin'],
}));

// 解析JSON请求体
app.use(express.json({ limit: '10mb' }));
app.use(express.urlencoded({ extended: true, limit: '10mb' }));

// 请求日志中间件
app.use((req, res, next) => {
  const startTime = Date.now();
  const requestId = Date.now().toString(36) + Math.random().toString(36).substr(2);
  
  req.requestId = requestId;
  req.startTime = startTime;
  
  logger.info('Incoming request', {
    requestId,
    method: req.method,
    url: req.url,
    ip: req.ip,
    userAgent: req.get('User-Agent')
  });
  
  // 记录响应时间
  res.on('finish', () => {
    const processingTime = Date.now() - startTime;
    logger.info('Request completed', {
      requestId,
      method: req.method,
      url: req.url,
      statusCode: res.statusCode,
      processingTime
    });
  });
  
  next();
});

// 连接 MongoDB
mongoose.connect(process.env.MONGODB_URI || 'mongodb://127.0.0.1:27017/traveller_social_app', {
  useNewUrlParser: true,
  useUnifiedTopology: true
})
.then(() => {
  console.log('✅ MongoDB连接成功');
})
.catch((error) => {
  console.error('❌ MongoDB连接失败:', error);
  process.exit(1);
});

// 监听MongoDB连接事件
mongoose.connection.on('connected', () => {
  console.log('📦 MongoDB已连接');
});

mongoose.connection.on('error', (err) => {
  console.error('❌ MongoDB连接错误:', err);
});

mongoose.connection.on('disconnected', () => {
  console.log('📦 MongoDB连接已断开');
});

// 基本路由
app.get('/', (req, res) => {
  res.json({
    message: '🚀 Travel App Backend API',
    version: '1.0.0',
    status: 'running',
    timestamp: new Date().toISOString()
  });
});

// 健康检查
app.get('/health', (req, res) => {
  res.json({
    status: 'healthy',
    database: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString()
  });
});

// API路由
app.use('/api/auth', authRoutes);
app.use('/api/users', userRoutes);
// app.use('/api/travel', travelRoutes); // 未使用，已注释
// app.use('/api/destinations', require('./routes/destinations')); // 未使用，已注释
app.use('/api/tours', require('./routes/tours'));
app.use('/api/hotels', require('./routes/hotels'));
app.use('/api/orders', require('./routes/orders'));
app.use('/api/foods', require('./routes/foods'));

// API健康检查
app.get('/api/health', (req, res) => {
  res.json({
    status: 'healthy',
    database: mongoose.connection.readyState === 1 ? 'connected' : 'disconnected',
    timestamp: new Date().toISOString(),
    version: '1.0.0'
  });
});

// 404处理
app.use('*', (req, res) => {
  res.status(404).json({
    error: '路径不存在',
    message: `找不到路径: ${req.originalUrl}`
  });
});

// 全局错误处理中间件
app.use((error, req, res, next) => {
  console.error('❌ 服务器错误:', error);
  
  res.status(error.status || 500).json({
    error: error.message || '服务器内部错误',
    ...(process.env.NODE_ENV === 'development' && { stack: error.stack })
  });
});

// 启动服务器
const PORT = process.env.PORT || 5000;
const server = app.listen(PORT, () => {
  console.log(`🚀 服务器运行在端口 ${PORT}`);
  console.log(`🌐 API地址: http://localhost:${PORT}`);
  console.log(`🔍 健康检查: http://localhost:${PORT}/health`);
});

// 优雅关闭
process.on('SIGTERM', gracefulShutdown);
process.on('SIGINT', gracefulShutdown);

function gracefulShutdown(signal) {
  console.log(`\n收到 ${signal} 信号，开始优雅关闭...`);
  
  server.close((err) => {
    if (err) {
      console.error('❌ 服务器关闭时出错:', err);
      process.exit(1);
    }
    
    mongoose.connection.close((err) => {
      if (err) {
        console.error('❌ MongoDB关闭时出错:', err);
        process.exit(1);
      }
      
      console.log('✅ 服务器和数据库连接已优雅关闭');
      process.exit(0);
    });
  });
} 